﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;

namespace ServEvo.ServConfig
{
    public delegate void dDownload(string reposUri);

    class UpdateManager
    {
        private ServEvoRepos.ServEvoRepos repos;
        private bool isX64 = true;
        private static UpdateManager manager;
        private ConfigurationManager _configuration;

        private UpdateManager(ConfigurationManager configuration)
        {
            this.repos = new ServEvoRepos.ServEvoRepos();
            this._configuration = configuration;
            //checkApacheVersion();
        }
        public static UpdateManager getManager(ConfigurationManager configuration)
        {
            if (UpdateManager.manager == null)
            {
                UpdateManager.manager = new UpdateManager(configuration);
            }

            return UpdateManager.manager;
        }

        public void checkCoreVersion()
        {
            string lastVersion = this.repos.getServEvoVersion();
            if (lastVersion != Properties.Resources.CURR_VERSION)
            {
                string lastVersionRepos = this.repos.getServEvoRepos(this.isX64);
                Thread th = new Thread(new ParameterizedThreadStart(getLastCore));
                th.Start(lastVersionRepos);
            }
        }

        public void getLastCore(object pRepo)
        {
            string sRepos = pRepo as string;
            string[] res = sRepos.Split(new string[] { "::" }, StringSplitOptions.None);
            Uri uriLastCore = new Uri(res[0]);
            if (uriLastCore.IsFile)
            {

            }
        }

        public void checkApacheVersion()
        {
            string lastVersion = this.repos.getApacheVersion();
            if (lastVersion != this._configuration.apacheVersion)
            {
                string lastVersionRepos = this.repos.getApacheRepos(this.isX64);
                Thread th = new Thread(new ParameterizedThreadStart(getLastApache));
                th.Start(lastVersionRepos);
            }
        }

        public void getLastApache(object pRepo)
        {
            string sRepos = pRepo as string;
            string[] res = sRepos.Split(new string[] { "::" }, StringSplitOptions.None);
            Uri uriLastCore = new Uri(res[0]);
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Accept", "application/zip");
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            webClient.DownloadFile(uriLastCore, @"D:\Serveurs\ServEvo\bin\apache\lastVersion.zip");
        }
    }
}
